package ext.acae2.statements;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;

import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.part.Quantity;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartHelper;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTRuntimeException;
import wt.vc.struct.StructHelper;
import wt.vc.views.ViewHelper;
import ext.acae2.statements.bean.ComponentCatalogBean;
import ext.acae2.util.IBAUtil;

public class ComponentCatalog {
	
	private static final Logger LOGGER = LogR.getLogger(ComponentCatalog.class.getName());
	
	public static void download(WTPart part, OutputStream output) 
            throws WTRuntimeException, WTException, IOException {
        LOGGER.debug("> Start download");
        
        String wthome = (String) WTProperties.getLocalProperties().get("wt.home");
        
        File templateFile = new File(wthome + File.separator 
                + "codebase" + File.separator + "ext" + File.separator 
                + "acae2" + File.separator + "conf" + File.separator
                + "ComponentCatalog.xls");
        
        List<ComponentCatalogBean> componentCatalogList = new ArrayList<ComponentCatalogBean>();
        creatComponentCatalogBean(part, componentCatalogList);
        
        for (ComponentCatalogBean componentCatalog : componentCatalogList) {
			selectAll(componentCatalog, componentCatalogList, Long.valueOf(componentCatalog.getParentPartQuantity()));
        }
        
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(templateFile));
        HSSFSheet sheet = workbook.getSheetAt(0);
        
        HSSFCellStyle seqCst = workbook.createCellStyle();
		seqCst.setBorderTop(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderRight(HSSFCellStyle.BORDER_THIN);
		seqCst.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        
        int rowNum = 4;
        write(componentCatalogList, rowNum, sheet, seqCst, part.getContainerName());
        
        workbook.write(output);
        output.flush();
        output.close();
        
        LOGGER.debug("> End download");
    }
	
	private static void creatComponentCatalogBean(WTPart part, List<ComponentCatalogBean> componentCatalogList) throws RemoteException, WTException{
		
//		if(part.getState().toString().equals("RELEASED")){
			
			if( (part.getNumber().length() == 13 && part.getNumber().substring(10,11).equals("M")) || ( part.getNumber().length() == 13 && part.getNumber().substring(10,11).equals("G"))){
				
				WTPartStandardConfigSpec standardConfigSpec = WTPartStandardConfigSpec
						.newWTPartStandardConfigSpec(
								ViewHelper.service.getView("Design"), null);
				WTPartConfigSpec configSpec = WTPartConfigSpec
						.newWTPartConfigSpec(standardConfigSpec);
				
//				QueryResult usageLinks = StructHelper.service.navigateUsedBy(part.getMaster(), false);
//				double singleStr = 0;
//				
//				while (usageLinks.hasMoreElements()) {
//					WTPartUsageLink alink = (WTPartUsageLink) usageLinks.nextElement();
//					Quantity quantity = alink.getQuantity();
//						
//					double singleQuantity = quantity.getAmount();
//					singleStr += singleQuantity;
//				}
				
				QueryResult childPartsQs = WTPartHelper.service.getUsesWTParts(part, configSpec);
				while (childPartsQs.hasMoreElements()) {
					ComponentCatalogBean componentCatalogBean = new ComponentCatalogBean();
					componentCatalogBean.setParentPartNumber(part.getNumber());
					
					Object obj[] = null;
					obj = (Object[]) childPartsQs.nextElement();
					if (obj[1] instanceof WTPart) {
						WTPart childPart = (WTPart) obj[1];
								
						WTPartUsageLink alink = (WTPartUsageLink) obj[0];
						Quantity quantity = alink.getQuantity();
								
						double singleQuantity = quantity.getAmount();
						String singleStrForParent = String.valueOf(singleQuantity).substring(0,String.valueOf(singleQuantity).lastIndexOf(".")).toString();
							
						componentCatalogBean.setNumber(childPart.getNumber());
						componentCatalogBean.setName(childPart.getName());
						IBAUtil iba = new IBAUtil(childPart);
						
						String characterType = "";
						if(iba.getIBAValue("characterType") != null){
							characterType = iba.getIBAValue("characterType");
						}
						
						if(characterType.equals("关键件")){
							characterType = "G";
						}else if(characterType.equals("重要件")){
							characterType = "Z";
						}
						
						componentCatalogBean.setCharacterType(characterType);
						componentCatalogBean.setVersion(childPart.getVersionIdentifier().getValue());
//						if(singleStr == 0){
//							componentCatalogBean.setQuantity("1");
//						}else{
//							componentCatalogBean.setQuantity(String.valueOf(singleStr).substring(0,String.valueOf(singleStr).lastIndexOf(".")).toString());
//						}
						componentCatalogBean.setParentPartQuantity(singleStrForParent);
						
//						if(childPart.getState().toString().equals("RELEASED")){
							if((childPart.getNumber().length() == 13 && childPart.getNumber().substring(10,11).equals("M")) || (childPart.getNumber().length() == 13 && childPart.getNumber().substring(10,11).equals("G"))){
								componentCatalogList.add(componentCatalogBean);
								creatComponentCatalogBean(childPart, componentCatalogList);
							}
//						}
					}
				}
			}
			
//		}
	}
	
	@SuppressWarnings({ "deprecation", "unchecked" })
	private static void write(List<ComponentCatalogBean> componentCatalogList, int rowNum, HSSFSheet sheet, HSSFCellStyle seqCst, String containerName){
		
		HSSFRow containerRow = sheet.createRow(1);
		containerRow.createCell(1);
		containerRow.getCell(1).setCellStyle(seqCst);
		containerRow.createCell(8).setCellValue(containerName);
		containerRow.getCell(8).setCellStyle(seqCst);

		String number = "";
		String name = "";
		String quantity = "";
		String characterType = "";
		String version = "";
		
		Collections.sort(componentCatalogList);
		
		for (ComponentCatalogBean componentCatalog : componentCatalogList) {
			HSSFRow row = sheet.createRow(rowNum);
           
			sheet.addMergedRegion(new Region(rowNum,(short)1,rowNum,(short)2)); 
			
			HSSFRow row1 = sheet.getRow(rowNum-1);
			
			// 组件号
            if(row1.getCell(0).getStringCellValue().equals(componentCatalog.getNumber()) || (row1.getCell(0).getStringCellValue() == "" && number.equals(componentCatalog.getNumber()))){
            	row.createCell(0).setCellValue("");
            }else{
            	row.createCell(0).setCellValue(componentCatalog.getNumber());
            }
            
            // 组件名称
            if((row1.getCell(1).getStringCellValue().equals(componentCatalog.getName()) && number.equals(componentCatalog.getNumber())) || (row1.getCell(3).getStringCellValue() == "" && name.equals(componentCatalog.getName()) && number.equals(componentCatalog.getNumber()))){
            	row.createCell(1).setCellValue("");
            }else{
            	row.createCell(1).setCellValue(componentCatalog.getName());
            }
            
            // 每台数量
            if((row1.getCell(3).getStringCellValue().equals(componentCatalog.getQuantity()) && number.equals(componentCatalog.getNumber())) || (row1.getCell(3).getStringCellValue() == "" && quantity.equals(componentCatalog.getQuantity()) && number.equals(componentCatalog.getNumber()))){
            	row.createCell(3).setCellValue("");
            }else{
            	row.createCell(3).setCellValue(componentCatalog.getQuantity());
            }
            
            // 标记
            if((row1.getCell(4).getStringCellValue().equals(componentCatalog.getCharacterType()) && number.equals(componentCatalog.getNumber())) || (row1.getCell(4).getStringCellValue() == "" && characterType.equals(componentCatalog.getCharacterType()) && number.equals(componentCatalog.getNumber()))){
            	row.createCell(4).setCellValue("");
            }else{
            	row.createCell(4).setCellValue(componentCatalog.getCharacterType());
            }
            
            // 版本
            if((row1.getCell(5).getStringCellValue().equals(componentCatalog.getVersion()) && number.equals(componentCatalog.getNumber())) || (row1.getCell(5).getStringCellValue() == "" && version.equals(componentCatalog.getVersion()) && number.equals(componentCatalog.getNumber()))){
            	row.createCell(5).setCellValue("");
            }else{
            	row.createCell(5).setCellValue(componentCatalog.getVersion());
            }
			
            // 装配处
            // 组件号
            row.createCell(6).setCellValue(componentCatalog.getParentPartNumber());
            // 数量
            row.createCell(7).setCellValue(componentCatalog.getParentPartQuantity());
            
            number = componentCatalog.getNumber();
            name = componentCatalog.getName();
            quantity = componentCatalog.getQuantity();
            characterType = componentCatalog.getCharacterType();
            version = componentCatalog.getVersion();
            
            rowNum++;
		}
	}
	
	private static void selectAll(ComponentCatalogBean componentCatalog, List<ComponentCatalogBean> componentCatalogList, Long l){
		for (ComponentCatalogBean componentCatalog1 : componentCatalogList) {
			if(componentCatalog.getNumber().equals(componentCatalog1.getParentPartNumber())){
				l = Long.valueOf(componentCatalog1.getParentPartQuantity()) * l;
				selectAll(componentCatalog1, componentCatalogList, l);
			}
			componentCatalog1.setQuantity(l+"");
    	}
	}
	
}
